Modify Bold Code

{ user ? (

<Link class="nav-link">Logout ({user})</Link>

) : (

<>

<Link class="nav-link" to={"/login"}>Login</Link>

<Link class="nav-link" to={"/signup"}>Sign Up</Link>

</>

)}

Login Logout

In this section, we will implement a preliminary login, logout and signup function and reflect the login state of a

user. Let ’ s first declare a user and token state variable using React hooks by adding the below in App.js:

Modify Bold Code

function App() {

const user = null;

const [user, setUser] = React.useState(null);

const [token, setToken] = React.useState(null);

const [error, setError] = React.useState('');

async function login(user = null){ // default user to null

setUser(user);

}

async function logout(){

setUser(null);

}

async function signup(user = null){ // default user to null

setUser(user);

}

Code Explanation

Analyze Code

const [user, setUser] = React.useState(null);

React.useState is a ‘ hook ’ that lets us add some local state to functional components. useState declares a ‘ state

variable ’ . React preserves this state between re-renders of the component. In our case, our state consists of a user

variable to represent either a logged in or logged out state. When we pass null to useState, i.e. useState(null), we

specify null to be the initial value for user.

useState returns an array with two values: the current state value and a function that lets you update it. In our case,

we assign the current state user value to user, and the function to update it to setUser.

Analyze Code

const [token, setToken] = React.useState(null);

const [error, setError] = React.useState('');

We also have a token state variable to represent the authorization token for the user and an error state variable to

store any error messages.

Analyze Code

async function login(user = null){ // default user to null

setUser(user);

}

async function logout(){

setUser(null);

}

async function signup(user = null){ // default user to null

setUser(user);

}

With login, we set the user state. The login function will be called from the Login component which we will

implement and re-visit later. signup for now works in a similar fashion. logout() simply sets user to null.

Later on, we will implement a full login system.